package com.bestdata.TD440.datahandle.service;

import cn.hutool.setting.Setting;
import com.alibaba.fastjson.JSONObject;
import com.bestdata.TD440.datahandle.model.DeviceInfoDto;
import com.bestdata.TD440.emNewModel.NewMessageSend;
import com.bestdata.TD440.emNewModel.model.DrsModelPOJO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.bestdata.TD440.datahandle.model.Map.dMap;

/**
 * @author
 */

@Service
@Lazy(false)
@EnableScheduling
@Configuration
public class Timmer{

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static String hid;

    private static Map<String, DeviceInfoDto>configMap = new HashMap<>();

    //private HashMap<String ,String> devMap = new HashMap();

    @Scheduled(cron = "0 */1 * * * ?")
    public void getMaxValue() {

        logger.info("Quartz is beginning....");

        if(dMap.size() > 0){

            HashMap<String,Object> cloneMap = new HashMap<>();

            //此处cloneMap的理由是设备采集测值持续向dMap中添加，只为取出同一时间两只设备测值
            cloneMap = dMap;

            logger.info("测值容器："+cloneMap);

            for (Map.Entry<String, Object> entry : cloneMap.entrySet()) {

                /**
                 *   2020年9月27日16:21:57 发现并解决问题：当高频率数据接收时，从map中取值并发送
                 *   会触发Unexpected error occurred in scheduled task异常，解决方案：定时器内部
                 *   创建线程，并调用转发服务，若不创建线程可能导致数据重复发送等问题
                 */
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //转发报文数据容器
                        LinkedHashMap<String,String> dataMap = new LinkedHashMap<>();
                        //获取设备序列号
                        DeviceInfoDto infoDto = configMap.get(entry.getKey());

                        DrsModelPOJO drsModelPOJO = new DrsModelPOJO();
                        drsModelPOJO.setSn(infoDto.getSn());
                        drsModelPOJO.setHid(hid);
                        drsModelPOJO.setTm(System.currentTimeMillis()+"");

                        logger.info(infoDto+"{}{}{}{}");
                        String value = "0";

                        if("0001".equals(infoDto.getModule()) && "0001".equals(infoDto.getSn())){
                            value = (Double.parseDouble(entry.getValue().toString())/0.00279393)+"";
                        }else if("0002".equals(infoDto.getModule()) && "0001".equals(infoDto.getSn())){
                            value = (Double.parseDouble(entry.getValue().toString())/0.00285258)+"";
                        }else{
                            value = entry.getValue().toString();
                        }

                        dataMap.put(infoDto.getAisle()+infoDto.getModule()+"0ZHD",value.substring(0,9));

                        drsModelPOJO.setData(dataMap);

                        logger.info("new Message Send To DRS ,DataPOJO  --->  {}"+drsModelPOJO);
                        try {
                            NewMessageSend.newMessageSendCore(JSONObject.toJSONString(drsModelPOJO));
                        } catch (Exception e) {
                            logger.error("new Message Send To DRS false !!!!!!!!!!!!!!!"+e);
                            e.printStackTrace();
                        }finally {

                        }
                    }
                }).start();
            }
            dMap.clear();
        }
    }


    @Value("${data.hid}")
    public void setHid(String hid) {
        Timmer.hid=hid;
    }

    @Value("${data.sns}")
    public void setSns(String sn) {

        String[] sns = sn.split(";");

        for (int i = 0; i < sns.length; i++) {
            String[] snAndConfig = sns[i].split(":");

            DeviceInfoDto dto = new DeviceInfoDto();
            dto.setDevId(snAndConfig[0]);
            dto.setAisle(snAndConfig[1]);
            dto.setModule(snAndConfig[2]);
            dto.setSn(snAndConfig[3]);
            configMap.put(dto.getDevId()+":"+dto.getAisle(),dto);
        }
        System.out.println(configMap);
    }
}
